package models

import (
	"fmt"
	"time"
	"xorm.io/builder"
)

type File struct {
	Id              int       `xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	LearnRecordId   int       `xorm:"comment('学时id外键关联dts_terminal表中的id') index INT(11)"`
	FileType        string    `xorm:"default '1' comment('文件类型：1：图片，2：视频，3：pdf ,4:声音') ENUM('1','2','3')"`
	FileUrl         string    `xorm:"not null comment('文件路径信息') VARCHAR(255)"`
	AddTime         time.Time `xorm:"not null comment('文件上传时间') index DATETIME"`
	InstitutionCode string    `xorm:"comment('运管统一编号') VARCHAR(16)"`
	VerifyStatus    string    `xorm:"default '0' comment('文件合法性审核状态，0：待审核，1：通过审核，2：未通过审核') ENUM('0','1','2')"`
	Status          string    `xorm:"default '0' comment('文件上传状态，0：未上传或上传失败，1：已上传') ENUM('0','1','2')"`
	FileNumber      string    `xorm:"comment('文件编号') VARCHAR(10)"`
	PhotoType       string    `xorm:"comment('发起照片的事件类型   0：中心查询的图片；1：紧急报警主动上传的图片；2：关车门后达到指定车速主动上传的图片；3：侧翻报警主动上传的图片；4：上客；5：定时拍照；6：进区域；7：出区域；8：事故疑点(紧急刹车)；9：开车门；17：学员登录拍照；18：学员登出拍照；19：学员培训过程中拍照；20：教练员登录拍照；21：教练员登出拍照') ENUM('0','1','17','18','19','2','20','21','3','4','5','6','7','8','9')"`
	Yuzhi           int       `xorm:"default 0 comment('照片阈值0-100') INT(11)"`
	Classid         int       `xorm:"default 0 comment('课堂id') index INT(11)"`
	GnssId          int       `xorm:"comment('gnss表主键id') INT(11)"`
}

type FileList struct {
	Id                      int
	FileType                string    `json:"file_type"`
	FileUrl                 string    `json:"file_url"`
	Status                  string    `json:"status"`
	FileNumber              string    `json:"file_number"`
	PhotoType               string    `json:"photo_type"`
	Classid                 int       `json:"classid"`
	RecordType              string    `json:"record_type"`
	AddTime                 time.Time `json:"add_time"`
	GnssDatetime            time.Time `json:"gnss_datetime"`
	GnssLongitude           float32   `json:"gnss_longitude"`
	GnssLatitude            float32   `json:"gnss_latitude"`
	GnssAlarmflag           int64     `json:"gnss_alarmflag"`
	GnssStatus              int64     `json:"gnss_status"`
	GnssMaxspeed            float64   `json:"gnss_maxspeed"`
	GnssVelocitycar         int64     `json:"gnss_velocitycar"`
	GnssOritentation        int64     `json:"gnss_oritentation"`
	Province                string    `json:"province"`
	District                string    `json:"district"`
	City                    string    `json:"city"`
	Subject                 string    `json:"subject"`
	StudentInstitutionCode  string    `json:"student_institution_code"`
	TerminalInstitutionCode string    `json:"terminal_institution_code"`
}

func (f *File) GetFileByLearnRecordId(id string) (list []*File, err error) {
	err = engine.Table("dts_file").
		Where("learn_record_id = ? and file_type = ?", id, "1").
		Find(&list)
	return list, err
}

// GetFileByPhotoType 根据学时id获取照片
func (f *File) GetFileByPhotoType(id int64) (list []*File, err error) {
	err = engine.Table("dts_file").Select("file_url").
		Where("learn_record_id = ? and file_type=? and photo_type  in ('17','18','19')", id, "1").
		Find(&list)
	return list, err
}

func (f *File) GetFileByRecordId(id int) (has bool, list File, err error) {
	has, err = engine.Table("dts_file").
		Where("learn_record_id = ? and file_type=? and photo_type = ?", id, "1", "18").
		Get(&list)
	return has, list, err
}

func (f *File) CheckFileByLearnRecordId(class_id int, start_time string) (has bool, list File, err error) {
	has, err = engine.Table("dts_file").Alias("fe").
		Join("LEFT", []string{"dts_learn_record", "ld"}, "fe.learn_record_id=ld.id").
		Where("ld.id = ? and ld.start_time >= ? and ld.start_time <= ? and fe.photo_type = ?", class_id, start_time+" 00:00:00", start_time+" 23:59:59", "18").
		Get(&list)
	return has, list, err
}

func (f *File) GetFileByRecord(id string) (list File, err error) {
	_, err = engine.Table("dts_file").
		Where("learn_record_id =? ", id).Desc("id").
		Get(&list)
	return list, err
}

func (f *File) CopyFile(startTime string, endTime string) (list []*File, err error) {
	list = make([]*File, 0)
	err = engine.Table("dts_file").
		Where("status = ?", "2").
		And(fmt.Sprintf("add_time > '%s'", startTime)).
		And(fmt.Sprintf("add_time < '%s'", endTime)).
		Find(&list)
	return list, err
}

func (f *File) GetFileList(cond builder.Cond) (list []*FileList, err error) {
	err = engine.Table("dts_file").Alias("f").
		Select("f.id,f.file_type,f.file_url,f.status,f.file_number,f.photo_type,f.classid,f.add_time,g.oritentation as gnss_oritentation,g.velocitycar as gnss_velocitycar,g.maxspeed as gnss_maxspeed,g.status as gnss_status,g.alarmflag as gnss_alarmflag,g.latitude as gnss_latitude,g.longitude as gnss_longitude,g.datetime as gnss_datetime,ld.subject,sl.province,ld.type as record_type,sl.district,sl.city,st.institution_code as student_institution_code,tr.institution_code as terminal_institution_code").
		Join("INNER", []string{"dts_learn_record", "ld"}, "ld.id = f.learn_record_id").
		Join("INNER", []string{"dts_school", "sl"}, "sl.id = ld.school_id").
		Join("INNER", []string{"dts_student", "st"}, "st.id = ld.student_id").
		Join("INNER", []string{"dts_terminal", "tr"}, "tr.id = ld.terminal_id").
		Join("INNER", []string{"dts_gnss", "g"}, "g.id = f.gnss_id").
		And(cond).Limit(3000).Find(&list)
	//log.Println(list, err)
	return

}

func (f *File) Edit(id int, data map[string]interface{}) bool {
	var (
		err error
	)
	engine.Table("dts_file").Where("id=?", id).Update(data)
	//log.Println(err)
	if err != nil {
		return false
	}
	return true
}

func (f *File) UpdateFileUrl(id int, url string) (err error) {
	_, err = engine.Table("dts_file").Exec("update dts_file set file_url = ? where id = ?", url, id)
	return err
}
